const path = require('path');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const webpack = require('webpack');
const bodyParser = require('body-parser');

module.exports = {
    entry:'./src/main.js',
    output:{
        filename:'build.js',
        path:path.resolve(__dirname,'./dist'),
        publicPath:'/dist/'
    },
    module:{
        rules:[
            {
                test:/\.vue$/,
                loader:'vue-loader'
            },
            // 它会应用到普通的 `.js` 文件
            // 以及 `.vue` 文件中的 `<script>` 块
            {
                test: /\.js$/,
                use:{
                    loader:'babel-loader',
                    options:{
                        presets:['@babel/preset-env']
                    }
                }
            },
            // 它会应用到普通的 `.css` 文件
            // 以及 `.vue` 文件中的 `<style>` 块
            {
                test: /\.css$/,
                use: [
                    'vue-style-loader',
                    'css-loader'
                ]
            }
        ]
    },
    plugins:[
        new VueLoaderPlugin(),
        new webpack.HotModuleReplacementPlugin()
    ],
    resolve:{
        alias:{
            'vue$':'vue/dist/vue.esm.js',
            '@':path.resolve(__dirname,'./src/components/')
        },
        extensions:['.vue','.js','scss','.css']
    },
    devtool:'cheap-module-eval-source-map',
    devServer:{
        hot:true,
        port:9090,
        contentBase:'.',
        before(app){
           app.get('/api/list',(req,res,next) => {
                let list = require('./mock/list.json');
                res.json({code:1,data:list})
            });

            app.post('/api/add',bodyParser.json(),(req,res,next) => {
                let list = require('./mock/list.json');
                req.body.time = Date.now();
                req.body.id = list.length;
                list.push(req.body);
                const fs = require('fs');
                fs.writeFile(path.join(__dirname,'mock','list.json'),JSON.stringify(list),(err) => {
                    if(err){
                        return res.json({code:0,msg:'添加失败'})
                    }
                    res.json({code:1,data:'添加成功'});
                })
            })
        }
    }
}